//
//  WmcAlbumSelectProjectsView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/22.
//

import UIKit
import YPBedrock

// MARK: - [WmcAlbumSelectProjectsView]

class WmcSystemAlbumSelectProjectsView: UIControl {
    // Lifecycle

    override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
        bindValue()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Internal

    lazy var maskLayer: CAShapeLayer = {
        let maskLayer = CAShapeLayer()
        return maskLayer
    }()

    lazy var listShadowView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = bottomCornerRadius
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowOffset = CGSize(width: 1, height: 3)
        view.layer.shadowRadius = bottomCornerRadius
        view.layer.shadowOpacity = 0.1
        return view
    }()

    lazy var tableContentView: UIView = {
        let view = UIView()
        return view
    }()

    lazy var tableView: UITableView = {
        let tableView = UITableView
            .YP.Create(style: .grouped, delegate: self, dataSource: self, registers: [
                YPRegister(WmcSystemAlbumSelectProjectsCell.self),
            ])
        tableView.rowHeight = 75.wmc_autoVer
        let height = Wmc_standardEdge.top + animationTopHideHeight
        let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 0, height: height)))
        tableView.tableHeaderView = view
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        return tableView
    }()

    let animationTopHideHeight: CGFloat = 100
    /// 相册列表
    let albumListRelay: BehaviorRelay<[WmcAlbumManager.AlbumModel]> = .init(value: [])
    /// 列表高度
    var listHeight: CGFloat = Wmc_screenHeight / 2
    /// 底部圆角半径
    var bottomCornerRadius: CGFloat = 8
    /// 列表选中回调
    var didSelectBlock: YPBlock.TwoParam<Int, WmcAlbumManager.AlbumModel>?

    override func layoutSubviews() {
        super.layoutSubviews()
        let maskPath = UIBezierPath(roundedRect: tableContentView.bounds,
                                    byRoundingCorners: [.bottomLeft, .bottomRight],
                                    cornerRadii: bottomCornerRadius.yp.cgSize)
        maskLayer.path = maskPath.cgPath
        tableContentView.layer.mask = maskLayer
    }

    func makeUI() {
        backgroundColor = .black.yp.alpha(0.3)
        addSubview(listShadowView)

        addSubview(tableContentView)
        tableContentView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(listHeight) // 默认高度
        }

        tableContentView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        listShadowView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(10)
            make.bottom.equalTo(tableView)
        }
    }

    func bindValue() {
        albumListRelay.subscribe(onNext: { [weak self] list in
            guard !list.isEmpty, // 空数组不处理
                  let weakSelf = self else { return }
            // 高度调整
            let rowHeight = weakSelf.tableView.rowHeight
            if list.count > 5 {
                weakSelf.listHeight = rowHeight * 5.5
            } else {
                weakSelf.listHeight = rowHeight * list.count.yp.cgFloat
            }
            weakSelf.listHeight += weakSelf.tableView.tableHeaderView?.frame.height ?? 0
            // 数据刷新
            weakSelf.tableView.reloadData()
        }).disposed(by: rx.disposeBag)
    }

    func showSelectView(_ isShow: Bool) {
        setNeedsUpdateConstraints()
        if isShow {
            startLayout(self)
            Wmc_SpringAnimation { [weak self] in
                guard let weakSelf = self else { return }
                endLayout(weakSelf)
                weakSelf.layoutIfNeeded()
            } completion: {}
        } else {
            endLayout(self)
            Wmc_SpringAnimation { [weak self] in
                guard let weakSelf = self else { return }
                startLayout(weakSelf)
                weakSelf.layoutIfNeeded()
            } completion: {}
        }

        func startLayout(_ weakSelf: WmcSystemAlbumSelectProjectsView) {
            weakSelf.tableContentView.snp.remakeConstraints { make in
                make.bottom.equalTo(weakSelf.snp.top).offset(-10)
                make.left.right.equalToSuperview()
                make.height.equalTo(listHeight)
            }
            layoutIfNeeded()
        }

        func endLayout(_ weakSelf: WmcSystemAlbumSelectProjectsView) {
            weakSelf.tableContentView.snp.remakeConstraints { make in
                make.top.equalTo(-animationTopHideHeight)
                make.left.right.equalToSuperview()
                make.height.equalTo(listHeight)
            }
            layoutIfNeeded()
        }
    }

    /// 选中某个
    /// 不会回调选中状态
    func select(at index: Int) {
        // 更新数组
        var newList: [WmcAlbumManager.AlbumModel] = []
        for (idx, album) in albumListRelay.value.enumerated() {
            let newAblum = album
            newAblum.isSelected = idx == index
            newList.append(newAblum)
        }
        albumListRelay.accept(newList)
    }
}

// MARK: - UITableViewDelegate

extension WmcSystemAlbumSelectProjectsView: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        select(at: indexPath.row)
        if let model = albumListRelay.value.yp.object(at: indexPath.row) { // 外出回调
            didSelectBlock?(indexPath.row, model)
        }
        YPDevice.PlayShake(.light)
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        YPDevice.PlayShake(.light)
    }
}

// MARK: - UITableViewDataSource

extension WmcSystemAlbumSelectProjectsView: UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return .YP.Min
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return albumListRelay.value.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WmcSystemAlbumSelectProjectsCell = tableView.yp.dequeueReusableCell()
        if let model = albumListRelay.value.yp.object(at: indexPath.row) {
            cell.configModel(model)
        }
        return cell
    }
}
